package com.bawei.bydayzg_two

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager.LayoutParams
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil.setContentView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.mvvm.BaseViewActivity
import com.bawei.base.room.MessageEntity
import com.bawei.base.room.UserUtils
import com.bawei.bydayzg_two.adapter.ImgAdapter
import com.bawei.bydayzg_two.adapter.MsgAdapter
import com.bawei.bydayzg_two.adapter.ONeAdapter
import com.bawei.bydayzg_two.databinding.ActivityMessageBinding
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import java.text.SimpleDateFormat

@Route(path = "/app/MessageActivity")
class MessageActivity : BaseViewActivity<ActivityMessageBinding>() {
    //展示对应商品的评论  所以需要一个商品id作为参数
    @Autowired
    @JvmField
    var goodsId = 1
    //
    var list:ArrayList<String> = arrayListOf()//用来储存上传的图片
    lateinit var imgAdapter: ImgAdapter
    lateinit var msgAdapter: MsgAdapter
    //
    override fun getLoutyId(): Int {
        return R.layout.activity_message
    }

    override fun initView() {
        //
        ARouter.getInstance().inject(this)
        //
        msgAdapter = MsgAdapter()
        binding.rvMsg.adapter = msgAdapter
        binding.rvMsg.layoutManager = LinearLayoutManager(this)
        //
        queryMsg()
        //弹出对话框
        binding.msgBtn.setOnClickListener {
            val popupWindow = PopupWindow()
            popupWindow.width = LayoutParams.MATCH_PARENT
            popupWindow.height = 700
            //创建一个布局
            val inflate = LayoutInflater.from(this).inflate(R.layout.pop_msg, null)
            //当输入的字数大于20时，我脑子变红
            inflate.findViewById<EditText>(R.id.pop_et).addTextChangedListener { text ->
                val count = inflate.findViewById<TextView>(R.id.pop_count)
                if (text != null){
                    //给字数显示
                    count.text = "${text.length}/20"
                    //颜色改变
                    if (text.toString().length == 20){
                        count.setTextColor(Color.RED)
                    } else {
                        count.setTextColor(Color.BLACK)
                    }
                }
            }

            //点击按钮上传图片  进行一次展示 ， 不超过3个‘
            inflate.findViewById<ImageView>(R.id.btn_up).setOnClickListener {
                if (list.size >= 3){
                    ToastUtils.showLong("最多上传3张图片")
                    return@setOnClickListener
                } else {
                    PictureSelector.create(this,200).selectPicture()
                }
            }
            //服用了评论的适配器和布局
            imgAdapter = ImgAdapter()
            val rv_img   = inflate.findViewById<RecyclerView>(R.id.rv_img)
            rv_img.adapter = imgAdapter
            rv_img.layoutManager = GridLayoutManager(this,3)

            //
            popupWindow.setOnDismissListener {
                list.clear()
            }
            //点击保存数据库
            inflate.findViewById<Button>(R.id.btn_send).setOnClickListener {
                var simpleDateFormat =SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val time = simpleDateFormat.format(System.currentTimeMillis())
                val messageEntity = MessageEntity(0,goodsId,
                    inflate.findViewById<EditText>(R.id.pop_et).text.toString(),
                    SPUtils.getInstance().getString("tel"),5f,time,
                    "${if (list.size > 0) list[0] else ""}",//至少选择一张图片
                    "${if (list.size > 1) list[1] else ""}",//至少选择两张图片
                    "${if (list.size > 2) list[2] else ""}")//至少选择三张图片
                //
                UserUtils.getDB().getMessage().insert(messageEntity)
                //
                ToastUtils.showLong("评论成功")
                popupWindow.dismiss()
                //实时更新
                queryMsg()
            }

            //
            popupWindow.contentView = inflate//设置布局
            popupWindow.isFocusable = true//获取焦点
            popupWindow.isOutsideTouchable = true//点击外部关闭
            popupWindow.showAtLocation(binding.msgBtn,Gravity.BOTTOM,0,0)
        }

        //滑动删除
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                var one = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
                return makeMovementFlags(0,one)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val adapterPosition = viewHolder.adapterPosition
                //
                UserUtils.getDB().getMessage().delete(msgAdapter.data[adapterPosition])
                //
                msgAdapter.data.removeAt(adapterPosition)
                msgAdapter.notifyItemRemoved(adapterPosition)
            }
        }).attachToRecyclerView(binding.rvMsg)
    }

    private fun queryMsg() {
        val list1 = UserUtils.getDB().getMessage().query(goodsId)
        msgAdapter.data.clear()
        msgAdapter.data.addAll(list1)
        msgAdapter.notifyDataSetChanged()
    }

    override fun initDate() {

    }
    //获取图片
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //
        if (requestCode == 200 && resultCode == RESULT_OK){
            val pictureBean = data!!.extras!!.get(PictureSelector.PICTURE_RESULT) as PictureBean
            list.add(pictureBean.path)
            //怎么显示到弹窗中
            imgAdapter.data.clear()
            imgAdapter.data.addAll(list)
            imgAdapter.notifyDataSetChanged()
        }
    }

}